<template>
    <!-- 图表 -->
    <div class="mychar-content">
        <div ref="refString" class="mychar"></div>
    </div>
</template>

<script setup>
import { defineProps, onMounted, toRefs, ref } from "vue";
import * as echarts from 'echarts';
const props = defineProps({
    echartsData: Array,
    echartsName: String
})
const { echartsData, echartsName } = toRefs(props)
const refString = ref('echarts')
const handlerEcharts = () => {
    const machart = echarts.init(refString.value);
    // 设置配置项
    const option = {
        title: {
            text: echartsName.value,
            left: 'center',
            top: '0',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            // bottom: '5%',
            left: 'center',
            top: '70%',
            // type: 'scroll',
            formatter: (name, e) => {
                echartsData.value.forEach(element => {
                    if (name == element.name) {
                        name = `${name}： ${element.value}`
                    }
                });
                return name;

            },
        },
        series: [
            {
                type: 'pie',
                center: ['50%', '40%'], // 调整饼图的位置
                radius: '55%', // 调整饼图的大小，使其左右对称
                avoidLabelOverlap: false,
                itemStyle: {
                    // borderRadius: 6,
                    borderColor: '#fff',
                    borderWidth: 1
                },
                label: {
                    show: false,
                    // position: 'center',
                    // fontWeight: 'bold',
                    // formatter: "{b} : {c}",
                    fontSize: 6,
                    // normal: {
                    //     show: true,
                    //     formatter: "{b} : {c}",
                    // },
                },
                labelLine: {
                    show: true,
                },
                data: echartsData.value
            }
        ]
    };
    machart.setOption(option);
    //动态获取窗口尺寸以便重置图表尺寸，用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
    window.addEventListener('resize', () => {
        if (machart) {
            machart.resize()
        }
    })
};
watch(echartsData, () => {
    handlerEcharts()
}, { deep: true })
onMounted(() => {
    handlerEcharts()
})
</script>

<style lang="scss" scoped>
.mychar-content {
    width: 100%;
    height: 100%;

    .mychar {
        width: 100%;
        height: 100%;
    }
}
</style>
